package io.github.zatter.qiniucorejava.utils;

import com.alibaba.fastjson2.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
@Component
public class QiniuOssUtil {

    // 从配置文件注入参数（不再硬编码）
//    @Value("${qiniu.access-key}")
    private String accessKey = "JmWswl3vOrevCWKOxeebarHqF1SFGulINAbv4R-g";

//    @Value("${qiniu.secret-key}")
    private String secretKey = "voXp9-Lma9E9DRUmGzctTy4a3X9moR8-DQ4pYFXD";

//    @Value("${qiniu.bucket-name}")
    private String bucketName = "qiniuaudio";

//    @Value("${qiniu.domain}")
    private String domain = "http://t33f8sh2i.hn-bkt.clouddn.com/";

//    @Value("${qiniu.region:z0}") // 默认华东区域
    private String region = "z2";

    // 根据配置的区域代码获取对应的Region对象
    private Region getRegion() {
        switch (region) {
            case "z0": return Region.region0(); // 华东
            case "z1": return Region.region1(); // 华北
            case "z2": return Region.region2(); // 华南
            case "na0": return Region.regionNa0(); // 北美
            case "as0": return Region.regionAs0(); // 东南亚
            default: return Region.region0(); // 默认值
        }
    }

    // 初始化上传管理器（使用配置的区域）
    private UploadManager getUploadManager() {
        Configuration cfg = new Configuration(getRegion());
        return new UploadManager(cfg);
    }

    // 生成上传凭证
    private String getUploadToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        return auth.uploadToken(bucketName);
    }

    /**
     * 上传文件到七牛云
     * @param file 上传的文件
     * @return 文件访问URL
     */
    public String uploadFile(MultipartFile file) throws IOException {
        try {
            // 生成唯一文件名（避免重复）
            String originalFilename = file.getOriginalFilename();
            String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + fileExt;

            // 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 上传文件
            UploadManager uploadManager = getUploadManager();
            Response response = uploadManager.put(inputStream, fileName, getUploadToken(), null, null);
            log.info("文件上传返回数据："+response);

            log.info("文件上传成功链接："+domain  + fileName);

            // 解析上传结果
//            DefaultPutRet putRet = JSON.JSONObject()
//                    .parseObject(response.bodyString(), DefaultPutRet.class);

            // 返回文件访问URL
            return domain + "/" + fileName;
        } catch (QiniuException e) {
            Response r = e.response;
            throw new IOException("七牛云上传失败：" + r.bodyString(), e);
        }
    }

    /**
     * 新增：直接上传字节数组到七牛云（无需MultipartFile）
     * @param audioBytes 音频字节数组
     * @param format 音频格式（mp3/wav）
     * @return 七牛云访问URL
     */
    public String uploadAudioBytes(byte[] audioBytes, String format) throws Exception {
        try {
            // 1. 生成唯一文件名（避免重复，格式：audio_UUID.xxx）
            String fileName = "audio_" + UUID.randomUUID().toString() + "." + format;
            // 2. 字节数组转输入流
            InputStream inputStream = new ByteArrayInputStream(audioBytes);

            // 3. 调用七牛SDK上传（与原有逻辑一致，只是输入流来源不同）
            UploadManager uploadManager = getUploadManager();
            String uploadToken = getUploadToken();
            Response response = uploadManager.put(inputStream, fileName, uploadToken, null, null);

            // 4. 校验上传结果
            if (!response.isOK()) {
                throw new Exception("七牛云上传失败，响应：" + response.bodyString());
            }
            log.info("字节流上传七牛云成功，文件名：{}", fileName);

            // 5. 返回访问URL
            return domain + fileName;
        } catch (QiniuException e) {
            Response r = e.response;
            throw new Exception("七牛云上传失败：" + r.bodyString(), e);
        }
    }

    /**
     * 删除七牛云文件
     * @param fileName 文件名（上传时返回的key）
     */
    public void deleteFile(String fileName) throws QiniuException {
        Configuration cfg = new Configuration(getRegion());
        com.qiniu.storage.BucketManager bucketManager = new com.qiniu.storage.BucketManager(
                Auth.create(accessKey, secretKey), cfg);
        
        Response response = bucketManager.delete(bucketName, fileName);
    }

    /**
     * 生成文件下载链接（带时效）
     * @param fileName 文件名
     * @param expireSeconds 链接有效期（秒）
     * @return 带签名的下载链接
     */
    public String getDownloadUrl(String fileName, long expireSeconds) {
        String baseUrl = "http://" + domain + "/" + fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        return auth.privateDownloadUrl(baseUrl, expireSeconds);
    }
}
    